<template>
  <div class="login-container">
    <el-form
      @submit.native.prevent="handleSubmit"
      :model="form"
      ref="form"
      :rules="rules"
      label-width="80px"
      class="login-form"
    >
      <h2 class="login-title">账号登录</h2>
      
      <el-form-item label="手机号" prop="accountName">
        <el-input 
          v-model="form.accountName" 
          placeholder="请输入手机号"
          maxlength="11"
        ></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="oldPassword">
        <el-input 
          type="password" 
          v-model="form.oldPassword" 
          placeholder="请输入密码"
          show-password
        ></el-input>
      </el-form-item>

      <el-form-item label="验证码" prop="captcha">
        <el-row :gutter="10">
          <el-col :span="11">
            <el-input 
              v-model="form.captcha" 
              placeholder="请输入验证码"
              maxlength="4"
            ></el-input>
          </el-col>
          <el-col :span="10">
            <canvas 
              ref="captchaCanvas" 
              class="captcha-canvas" 
              @click="generateCaptcha"
              title="点击刷新验证码"
            ></canvas>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item>
        <el-button 
          type="primary" 
          @click="handleSubmit" 
          class="login-button"
          :loading="loading"
        >
          登录
        </el-button>
        <el-button type="text" @click="showForgotPasswordDialog">忘记密码</el-button>
      </el-form-item>
    </el-form>

    <!-- 忘记密码对话框 -->
    <el-dialog 
      title="忘记密码" 
      :visible.sync="forgotPasswordDialogVisible"
      @close="handleDialogClose"
    >
      <el-form 
        :model="forgotPasswordForm" 
        ref="forgotPasswordForm" 
        :rules="forgotPasswordRules" 
        label-width="100px"
      >
        <el-form-item label="手机号" prop="accountName">
          <el-input v-model="forgotPasswordForm.accountName"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-row :gutter="10">
            <el-col :span="16">
              <el-input v-model="forgotPasswordForm.code"></el-input>
            </el-col>
            <el-col :span="8">
              <el-button 
                @click="sendSms" 
                :disabled="smsTimer > 0"
                :loading="smsSending"
              >
                {{ smsTimer > 0 ? `${smsTimer}s后重试` : '发送验证码' }}
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="旧密码" prop="password">
          <el-input 
            type="oldPassword" 
            v-model="forgotPasswordForm.oldPassword" 
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input 
            type="password" 
            v-model="forgotPasswordForm.password" 
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="resetPassword" :loading="resetting">
            重置密码
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号'));
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号'));
      } else {
        callback();
      }
    };

    return {
      // 登录表单数据
      form: {
        accountName: '',
        oldPassword: '',
        captcha: ''
      },
      // 登录表单验证规则
      rules: {
        accountName: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        oldPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      // 图形验证码
      generatedCaptcha: '',
      loading: false,

      // 忘记密码表单数据
      forgotPasswordForm: {
        accountName: '',
        code: '',
        password: '',
        oldPassword: ''
      },
      // 忘记密码表单验证规则
      forgotPasswordRules: {
        accountName: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ]
      },
      // 控制忘记密码对话框显示
      forgotPasswordDialogVisible: false,
      // 短信验证码倒计时
      smsTimer: 0,
      // 发送短信loading
      smsSending: false,
      // 重置密码loading
      resetting: false
    };
  },
  methods: {
    // 生成图形验证码
    generateCaptcha() {
      const canvas = this.$refs.captchaCanvas;
      const ctx = canvas.getContext('2d');
      const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
      let captcha = '';

      // 生成随机验证码
      for (let i = 0; i < 4; i++) {
        captcha += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      this.generatedCaptcha = captcha;

      // 设置画布大小
      canvas.width = 120;
      canvas.height = 40;

      // 清空画布
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // 设置背景
      ctx.fillStyle = '#f0f0f0';
      ctx.fillRect(0, 0, canvas.width, canvas.height);

      // 绘制干扰线
      for (let i = 0; i < 3; i++) {
        ctx.strokeStyle = this.getRandomColor(40, 180);
        ctx.beginPath();
        ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.stroke();
      }

      // 绘制干扰点
      for (let i = 0; i < 30; i++) {
        ctx.fillStyle = this.getRandomColor(0, 255);
        ctx.beginPath();
        ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, 2 * Math.PI);
        ctx.fill();
      }

      // 绘制验证码
      ctx.font = 'bold 24px Arial';
      ctx.textBaseline = 'middle';
      for (let i = 0; i < captcha.length; i++) {
        ctx.fillStyle = this.getRandomColor(40, 180);
        ctx.save();
        ctx.translate(30 * i + 15, 20);
        ctx.rotate((Math.random() - 0.5) * 0.4);
        ctx.fillText(captcha[i], 0, 0);
        ctx.restore();
      }
    },

    // 生成随机颜色
    getRandomColor(min, max) {
      const r = Math.floor(Math.random() * (max - min) + min);
      const g = Math.floor(Math.random() * (max - min) + min);
      const b = Math.floor(Math.random() * (max - min) + min);
      return `rgb(${r},${g},${b})`;
    },

    // 登录提交
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 验证码校验
          if (this.form.captcha.toLowerCase() !== this.generatedCaptcha.toLowerCase()) {
            this.$message.error('验证码错误');
            this.generateCaptcha();
            this.form.captcha = '';
            return;
          }

          this.loading = true;
          this.$axios.post('/api/user-server/user/phoneLogin', this.form)
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success('登录成功');
                // 存储用户信息
                localStorage.setItem('userId', response.data.data.id);
                localStorage.setItem('username', response.data.data.accountName);
                localStorage.setItem('token', response.data.data.accountName);
                // 跳转到工作台
                this.$router.push('/workbench');
              } else {
                this.$message.error(response.data.msg || '登录失败');
                this.generateCaptcha();
              }
            })
            .catch(error => {
              console.error('登录失败:', error);
              this.$message.error('登录失败，请稍后重试');
              this.generateCaptcha();
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },

    // 显示忘记密码对话框
    showForgotPasswordDialog() {
      this.forgotPasswordDialogVisible = true;
    },

    // 发送短信验证码
    sendSms() {
      this.$refs.forgotPasswordForm.validateField('accountName', (valid) => {
        if (!valid) {
          this.smsSending = true;
          const params = {
            accountName: this.forgotPasswordForm.accountName
          };

          console.log('发送验证码参数:', params); // 调试用

          this.$axios.get('/api/user-server/user/getCode/'+ this.forgotPasswordForm.accountName) 
            .then(response => {
              console.log('验证码响应:', response.data); // 调试用
              if (response.data.code === 200) {
                this.$message.success('验证码已发送');
                this.smsTimer = 60;
                const timer = setInterval(() => {
                  this.smsTimer--;
                  if (this.smsTimer <= 0) {
                    clearInterval(timer);
                  }
                }, 1000);
              } else {
                this.$message.error(response.data.msg || '发送失败');
              }
            })
            .catch(error => {
              console.error('发送验证码失败:', error);
              this.$message.error('发送失败，请重试');
            })
            .finally(() => {
              this.smsSending = false;
            });
        }
      });
    },

    // 重置密码
    resetPassword() {
      this.$refs.forgotPasswordForm.validate(valid => {
        if (valid) {
          this.resetting = true;
          const params = {
            accountName: this.forgotPasswordForm.accountName,
            code: this.forgotPasswordForm.code,
            password: this.forgotPasswordForm.password,
            oldPassword: this.forgotPasswordForm.oldPassword
          };

          console.log('重置密码参数:', params); // 调试用

          this.$axios.post('/api/user-server/user/changePassword', params)
            .then(response => {
              console.log('重置密码响应:', response.data); // 调试用
              if (response.data.code === 200) {
                this.$message.success('密码重置成功');
                this.forgotPasswordDialogVisible = false;
                this.$refs.forgotPasswordForm.resetFields();
              } else {
                this.$message.error(response.data.msg || '重置失败');
              }
            })
            .catch(error => {
              console.error('重置密码失败:', error);
              this.$message.error('重置失败，请重试');
            })
            .finally(() => {
              this.resetting = false;
            });
        }
      });
    },

    // 关闭对话框时重置表单
    handleDialogClose() {
      this.$refs.forgotPasswordForm.resetFields();
      this.smsTimer = 0;
    }
  },
  mounted() {
    this.generateCaptcha(); // 初始生成验证码
  }
};
</script>

<style scoped>
.login-container {
  width: 400px;
  margin: 100px auto;
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
  font-size: 24px;
}

.login-form {
  max-width: 100%;
}

.login-button {
  width: 100%;
  margin-bottom: 10px;
}

.captcha-canvas {
  width: 120px;
  height: 40px;
  cursor: pointer;
  vertical-align: middle;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

/* 响应式设计 */
@media screen and (max-width: 480px) {
  .login-container {
    width: 90%;
    margin: 50px auto;
    padding: 15px;
  }
}
</style>